<?php
/**
 * Redis 缓存测试程序
 * 用于验证 Redis 保存和读取会员信息是否成功
 */

// 读取 .env 配置
function loadDotEnv(string $path): array {
    if (!is_file($path)) return [];
    $vars = [];
    foreach (file($path) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        $pos = strpos($line, '=');
        if ($pos === false) continue;
        $key = trim(substr($line, 0, $pos));
        $val = trim(substr($line, $pos + 1));
        if ((strlen($val) >= 2) && (($val[0] === '"' && substr($val, -1) === '"') || ($val[0] === "'" && substr($val, -1) === "'"))) {
            $val = substr($val, 1, -1);
        }
        $vars[$key] = $val;
    }
    return $vars;
}

// 加载配置
$env = loadDotEnv(__DIR__ . '/../../.env');
$redisConfig = [
    'host' => $env['REDIS_HOST'] ?? getenv('REDIS_HOST') ?: '127.0.0.1',
    'port' => $env['REDIS_PORT'] ?? getenv('REDIS_PORT') ?: 6379,
    'password' => $env['REDIS_PASSWORD'] ?? getenv('REDIS_PASSWORD') ?: '',
    'database' => $env['REDIS_DATABASE'] ?? getenv('REDIS_DATABASE') ?: 0
];

echo "========================================\n";
echo "Redis 缓存测试程序\n";
echo "========================================\n\n";

echo "📋 Redis 配置信息：\n";
echo "  Host: {$redisConfig['host']}\n";
echo "  Port: {$redisConfig['port']}\n";
echo "  Database: {$redisConfig['database']}\n";
echo "  Password: " . (empty($redisConfig['password']) ? '无' : '已设置') . "\n\n";

// 连接 Redis
echo "🔗 正在连接 Redis...\n";
try {
    $redis = new Redis();
    $redis->connect($redisConfig['host'], $redisConfig['port'], 2);

    if (!empty($redisConfig['password'])) {
        echo "   使用密码认证...\n";
        $redis->auth($redisConfig['password']);
    }

    $redis->select($redisConfig['database']);
    echo "✅ Redis 连接成功！\n\n";
} catch (\Throwable $e) {
    echo "❌ Redis 连接失败：" . $e->getMessage() . "\n";
    echo "\n💡 提示：\n";
    echo "   1. 检查 Redis 是否正在运行\n";
    echo "   2. 检查 .env 中的 REDIS_PASSWORD 是否正确\n";
    echo "   3. 检查 Redis 服务器地址和端口是否正确\n";
    exit(1);
}

// 测试数据
$testMemberId = 123;
$testMemberData = [
    'id' => $testMemberId,
    'name' => '测试用户',
    'card_no' => 'CARD123456',
    'store_id' => 1,
    'total_points' => 500
];

$cacheKey = "member:{$testMemberId}";

echo "📝 测试数据：\n";
echo "  Member ID: {$testMemberId}\n";
echo "  Cache Key: {$cacheKey}\n";
echo "  Data: " . json_encode($testMemberData, JSON_UNESCAPED_UNICODE) . "\n\n";

// 测试 1: 保存数据
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "测试 1️⃣ : 保存数据到 Redis\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

try {
    $result = $redis->setex($cacheKey, 86400, json_encode($testMemberData, JSON_UNESCAPED_UNICODE));
    if ($result) {
        echo "✅ 数据保存成功！\n";
        echo "   Key: {$cacheKey}\n";
        echo "   TTL: 86400 秒（24小时）\n";
        echo "   Value: " . json_encode($testMemberData, JSON_UNESCAPED_UNICODE) . "\n\n";
    } else {
        echo "❌ 数据保存失败！\n\n";
    }
} catch (\Throwable $e) {
    echo "❌ 保存出错：" . $e->getMessage() . "\n\n";
}

// 测试 2: 读取数据
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "测试 2️⃣ : 从 Redis 读取数据\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

try {
    $data = $redis->get($cacheKey);
    if ($data) {
        $memberData = json_decode($data, true);
        echo "✅ 数据读取成功！\n";
        echo "   Key: {$cacheKey}\n";
        echo "   Value: " . json_encode($memberData, JSON_UNESCAPED_UNICODE) . "\n";
        echo "   Member Name: {$memberData['name']}\n";
        echo "   Total Points: {$memberData['total_points']}\n\n";
    } else {
        echo "❌ 数据不存在或已过期！\n\n";
    }
} catch (\Throwable $e) {
    echo "❌ 读取出错：" . $e->getMessage() . "\n\n";
}

// 测试 3: 检查 TTL
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "测试 3️⃣ : 检查数据过期时间\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

try {
    $ttl = $redis->ttl($cacheKey);
    if ($ttl > 0) {
        echo "✅ 数据有效！\n";
        echo "   剩余 TTL: {$ttl} 秒\n";
        echo "   约 " . round($ttl / 3600, 2) . " 小时后过期\n\n";
    } else {
        echo "❌ 数据已过期或不存在！\n\n";
    }
} catch (\Throwable $e) {
    echo "❌ 检查出错：" . $e->getMessage() . "\n\n";
}

// 测试 4: 删除数据
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "测试 4️⃣ : 删除 Redis 中的数据\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

try {
    $result = $redis->del($cacheKey);
    if ($result > 0) {
        echo "✅ 数据删除成功！\n";
        echo "   删除的 Key 数: {$result}\n\n";
    } else {
        echo "⚠️  没有找到要删除的数据\n\n";
    }
} catch (\Throwable $e) {
    echo "❌ 删除出错：" . $e->getMessage() . "\n\n";
}

// 测试 5: 验证删除
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "测试 5️⃣ : 验证数据已删除\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

try {
    $data = $redis->get($cacheKey);
    if ($data === false) {
        echo "✅ 数据已成功删除！\n";
        echo "   Key: {$cacheKey} 不存在\n\n";
    } else {
        echo "❌ 数据仍然存在！\n\n";
    }
} catch (\Throwable $e) {
    echo "❌ 验证出错：" . $e->getMessage() . "\n\n";
}

// 总结
echo "========================================\n";
echo "✅ 所有测试完成！\n";
echo "========================================\n";
echo "\n如果所有测试都显示 ✅，说明 Redis 工作正常。\n";
echo "现在可以在生产环境中使用 Redis 缓存了！\n";

$redis->close();
?>

